<template>
<van-button
  v-if="followFlag"
  round
  size="small"
  @click="onFollow"
  :loading="isFollowLoading"
>已关注</van-button>
<van-button
  v-else
  type="info"
  color="#3296fa"
  round
  size="small"
  icon="plus"
  @click="onFollow"
  :loading="isFollowLoading"
>关注</van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'

export default {
  model: {
    prop: 'followFlag',
    event: 'updatefollowFlag'
  },
  props: {
    followFlag: {
      type: Boolean,
      required: true
    },
    targetId: {
      type: [String, Number, Object],
      required: true
    }
  },
  data () {
    return {
      isFollowLoading: false
    }
  },

  created () {

  },

  methods: {
    async onFollow () {
      this.isFollowLoading = true
      try {
        if (this.followFlag) {
          await deleteFollow(this.targetId)
          this.$toast('取消关注成功')
        } else {
          await addFollow(this.targetId)
          this.$toast('添加关注成功')
        }
        this.$emit('updatefollowFlag', !this.followFlag)
      } catch (err) {
        let message = '操作失败，请稍后重试！'
        if (err.response && err.response.status === 400) {
          message = '你不能关注自己'
        }
        this.$toast(message)
      }
      this.isFollowLoading = false
    }
  }
}
</script>

<style scoped lang='less'>

</style>
